package chagine.core.restful.mvc;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.*;

/**
 * com.seeing.restful.filter.MutableHttpServletRequest
 * Created by 王彬安（wba）on 2018/7/2.
 */
public class MutableHttpServletRequest extends HttpServletRequestWrapper {
    // holds custom header and value mapping
    private final Map<String, String> customHeaders = new HashMap<String, String>();

    /**
     * 请求报文
     */
    private String requestBody = null;

    public MutableHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    public void setRequestBody(String requestBody) {
        this.requestBody = requestBody;
    }

    public void putHeader(String name, String value) {
        this.customHeaders.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        // check the custom headers first
        String headerValue = customHeaders.get(name);

        if (headerValue != null) {
            return headerValue;
        }
        // else return from into the original wrapped object
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        if (customHeaders.containsKey(name)) {
            Set<String> set = new HashSet<String>(1);
            set.add(customHeaders.get(name));
            return Collections.enumeration(set);
        } else {
            return super.getHeaders(name);
        }
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        // create a set of the custom header names
        Set<String> set = new HashSet<String>(customHeaders.keySet());

        // now add the headers from the wrapped request object
        @SuppressWarnings("unchecked")
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            // add the names of the request headers into the list
            String n = e.nextElement();
            set.add(n);
        }

        // create an enumeration from the set and return
        return Collections.enumeration(set);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.ServletRequestWrapper#getReader()
     */
    @Override
    public BufferedReader getReader() throws IOException {
        if (requestBody == null) {
            return super.getReader();
        }
        return new BufferedReader(new StringReader(requestBody));
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.ServletRequestWrapper#getInputStream()
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (requestBody == null) {
            return super.getInputStream();
        }

        return new ServletInputStream() {

            private InputStream in = new ByteArrayInputStream(requestBody.getBytes(getRequest().getCharacterEncoding()));

            @Override
            public boolean isFinished() {
                try {
                    return in.available() <= 0;
                } catch (IOException e) {
                    return false;
                }
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return in.read();
            }
        };
    }
}